#import "XSelector.h"

#import "XMacro.h"
#import "UIView+X.h"
#import "UIColor+X.h"
#import "XLayerController.h"


NSString * const KEY_SELECTORITEM_TITLE                     = @"Title";         // 选项名称，将作为item的标题显示（不能为空）
NSString * const KEY_SELECTORITEM_IMAGE                     = @"Image";         // 列表当中显示的图片（可选）
NSString * const KEY_SELECTORITEM_DETAIL                    = @"Detail";        // 详情信息（可选）

NSInteger const SELECTORITEM_CELLHEIGHT                     = 44;


typedef enum _SelectorStyleEnum {
    StringItemSelector,                 // 简单模式——字符串对象
    DictionaryItemSelector,             // 简单模式——词典对象
    DetailDictionaryItemSelector        // 详情模式——地点对象
} SelectorStyleEnum;


@interface XSelector () <UITableViewDataSource, UITableViewDelegate> {
    NSString    *m_strTitle;                    // 标题
    NSArray     *m_arrItems;                    // 选项
    NSString    *m_strKey;                      // 指定的Key
    SelectorStyleEnum           m_Style;        // 选择器样式
    id<XSelectorDelegate>       m_Delegate;     // 回调对象
}

@end


@implementation XSelector


/**
 * 设置类型
 * @param        style，选择器的类型
 * @result
 */
- (void)setStyle:(SelectorStyleEnum)style {
    m_Style = style;
}


/**
 * 创建标题
 * @param        title，标题
 * @result       返回创建的标题控件的视图
 */
- (UIView *)createTitle:(NSString *)title {
    // 记录相关的参数
    m_strTitle = title;
    
    CGRect rc = CGRectMake(10, 0, self.frame.size.width, 40);
    rc.size.width -= rc.origin.x * 2;
    UIView *vTitleBG = [[UIView alloc] initWithFrame:rc];
    vTitleBG.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"DracodeSDK_MsgBoxTitleBG.png"]];
    [vTitleBG addCornerBorderWithColor:[UIColor clearColor]];
    
    if (title && title.length > 0) {
        // 有标题的时候，才创建标题
        rc = vTitleBG.frame;
        rc.origin = CGPointZero;
        rc.origin.x += 10;
        rc.size.width -= 10 * 2;
        UILabel *labTitle = [[UILabel alloc] initWithFrame:rc];
        labTitle.backgroundColor = [UIColor clearColor];
        labTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
        labTitle.textAlignment = UITextAlignmentCenter;
        labTitle.textColor = [UIColor whiteColor];
        labTitle.text = title;
        [vTitleBG addSubview:labTitle];
    }
    
    return vTitleBG;
}


/**
 * 创建选项 Table
 * @param        items，需要插入Table的Items
 * @param        key，需要插入Table的Items，对应的Key
 * @result
 */
- (UITableView *)createItemsTable:(NSArray *)items withKey:(NSString *)key {
    if (nil == items || items.count == 0) {
        NSLog(@"参数错误！选项不能为空！");
        return nil;
    }
    
    // 记录相关参数
    m_arrItems = items;
    m_strKey = key;
    
    // 创建Table
    BOOL bScrollEnabled = YES;
    CGRect rc = CGRectMake(10, 0, self.frame.size.width - 20, 330);
    if (SELECTORITEM_CELLHEIGHT * items.count < rc.size.height) {
        rc.size.height = SELECTORITEM_CELLHEIGHT * items.count;
        bScrollEnabled = NO;
    }
    UITableView *tvItems = [[UITableView alloc] initWithFrame:rc];
    tvItems.backgroundColor = [UIColor clearColor];
    tvItems.dataSource = self;
    tvItems.delegate = self;
    tvItems.separatorStyle = UITableViewCellSeparatorStyleNone;
    tvItems.scrollEnabled = bScrollEnabled;
    
    return tvItems;
}


/**
 * 关闭当前告警框
 * @result
 */
- (void)close {
    [XLayerController removeLayer:self];
}


/**
 * 显示
 * @result
 */
- (void)show:(NSString *)title
   withItems:(NSArray *)items
      andKey:(NSString *)key
    delegate:(id/*<ItemsSelectorDelegate>*/)delegate {
    if (nil == items || items.count == 0) {
        NSLog(@"参数错误！选项不能为空！");
        return;
    }
    
    // 记录相关的参数
    m_Delegate = delegate;
    
    // 用于记录主窗体的布局
    CGRect rc;
    CGRect rcMain = CGRectMake(20, 0, 280, 0);
    
    // 编辑主窗体 背景颜色
    self.backgroundColor = [UIColor whiteColor];
    self.frame = rcMain;
    [self addCornerBorderWithColor:[UIColor clearColor]];
    
    // 创建标题
    UIView *vTitle = [self createTitle:title];
    rc = vTitle.frame;
    rc.origin.y += 10;
    vTitle.frame = rc;
    [self addSubview:vTitle];
    rcMain.size.height = vTitle.frame.origin.y + vTitle.frame.size.height;
    
    // 创建选项表
    UITableView *tvItems = [self createItemsTable:items withKey:key];
    rc = tvItems.frame;
    rc.origin.y += vTitle.frame.origin.y + vTitle.frame.size.height + 10;
    tvItems.frame = rc;
    [self addSubview:tvItems];
    rcMain.size.height = tvItems.frame.origin.y + tvItems.frame.size.height;
    
    // 调整主窗体布局
    rcMain.size.height += 10;
    rcMain.origin.y = ([[UIScreen mainScreen] bounds].size.height - rcMain.size.height) / 2;
    self.frame = rcMain;
    
    // 显示窗体
    [XLayerController addLayer:self withFocus:YES andBackgroundClose:YES];
}


/**
 * 简单选项模式（只有一行文字的选项框）
 * @param        title，弹出框对应的标题信息
 * @param        items，选项数组，每个元素为一个字符串NSString，作为item的标题显示出来
 * @param        delegate，处理选项选中后的回调对象，对象当中需实现 - (void)selectItem:(NSString*)title index:(NSUInteger)uIndex 方法
 * @result
 */
+ (void)showSelector:(NSString*)title
           withItems:(NSArray*)items
            delegate:(id/*<ItemsSelectorDelegate>*/)delegate {
    XSelector *v = [[XSelector alloc] init];
    [v setStyle:StringItemSelector];
    [v show:title withItems:items andKey:nil delegate:delegate];
}


/**
 * 简单选项模式-词典元素（只有一行文字的选项框）
 * @param        title，弹出框对应的标题信息
 * @param        items，选项数组，每个元素为一个词典数据，根据传入的Key，获取相应的字段，作为item的标题显示出来
 * @param        key，词典元素对应的Key值，根据该Key值获取词典元素当中对应的字段，作为item的标题显示出来
 * @param        delegate，处理选项选中后的回调对象，对象当中需实现 - (void)selectItem:(NSString*)title index:(NSUInteger)uIndex 方法
 * @result
 */
+ (void)showSelector:(NSString*)title
        withDicItems:(NSArray*)items
              andKey:(NSString*)key
            delegate:(id/*<ItemsSelectorDelegate>*/)delegate {
    XSelector *v = [[XSelector alloc] init];
    [v setStyle:DictionaryItemSelector];
    [v show:title withItems:items andKey:key delegate:delegate];
}


/**
 * 简单选项模式-词典元素（只有一行文字的选项框）
 * @param        title，弹出框对应的标题信息
 * @param        items，选项数组，每个元素为一个字典NSDictionary 含有对象：
 *                      KEY             值类型                 说明
 *                      Title           NSString              选项名称，将作为item的标题显示（不能为空）
 *                      Image           UIImage               列表当中显示的图片（可选）
 *                      Detail          NSString              详情信息（可选）
 * @param        key，词典元素对应的Key值，根据该Key值获取词典元素当中对应的字段，作为item的标题显示出来
 * @param        delegate，处理选项选中后的回调对象，对象当中需实现 - (void)selectItem:(NSString*)title index:(NSUInteger)uIndex 方法
 * @result
 */
+ (void)showDetailSelector:(NSString*)title
                 withItems:(NSArray*)items
                  delegate:(id/*<ItemsSelectorDelegate>*/)delegate {
    XSelector *v = [[XSelector alloc] init];
    [v setStyle:DetailDictionaryItemSelector];
    [v show:title withItems:items andKey:nil delegate:delegate];
}


#pragma mark UITableViewDelegate UIDatasourceDelegate
/**
 * 返回表中指定 Section 的行数
 * @param   tableView               UITableView 类型，表对象
 * @param   section                 NSInteger 类型，Section 的对应索引
 * @result                          NSInteger 类型，Section 当中记录的行数
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return m_arrItems ? m_arrItems.count : 0;
}


/**
 * 返回列表当中行的高度
 * @param   tableView               UITableView 类型，表对象
 * @param   indexPath               NSIndexPath 类型，表中记录的索引信息
 * @result                          CGFloat 类型，记录行高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SELECTORITEM_CELLHEIGHT;
}


/**
 * 返回列表当中所需的单元格对象
 * @param   tableView               UITableView 类型，表对象
 * @param   indexPath               NSIndexPath 类型，表中记录的索引信息
 * @result                          UITableViewCell 类型，单元格对象
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger nRow = indexPath.row;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selector"];
    if (!cell) {
        UITableViewCellStyle style = UITableViewCellStyleDefault;
        if (m_Style == DetailDictionaryItemSelector) {
            style = UITableViewCellStyleSubtitle;
        }
        cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"selector"];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        // 分割线
        CGRect rc = CGRectMake(0, 1, cell.frame.size.width, 1);
        UIView *vLine = [[UIView alloc] initWithFrame:rc];
        vLine.backgroundColor = [UIColor colorWithHex:0xd1d1d1];
        vLine.tag = 1001;
        [cell addSubview:vLine];
        
        // 单元格选中时的背景
//        UIView *view = [[UIView alloc] initWithFrame:cell.frame];
//        view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"icon_highlighted.png"]];
//        cell.selectedBackgroundView = view;
//        [view release];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 修改字体
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16.0f];
        cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0f];
        
        // 修改字体颜色
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.highlightedTextColor = [UIColor blackColor];
        cell.detailTextLabel.textColor = [UIColor darkGrayColor];
        cell.detailTextLabel.highlightedTextColor = [UIColor darkGrayColor];
    }
    
    // 处理单元格内容填充
    if (StringItemSelector == m_Style) {
        NSString *strTitle = [m_arrItems objectAtIndex:nRow];
        cell.textLabel.text = strTitle;
    }
    else if (DictionaryItemSelector == m_Style) {
        NSDictionary *dicItem = [m_arrItems objectAtIndex:nRow];
        NSString *strTitle = [dicItem objectForKey:m_strKey];
        cell.textLabel.text = strTitle;
    }
    else if (DetailDictionaryItemSelector == m_Style) {
        NSDictionary *dicItem = [m_arrItems objectAtIndex:nRow];
        NSString *strTitle = [dicItem objectForKey:KEY_SELECTORITEM_TITLE];
        cell.textLabel.text = strTitle;
        
        cell.imageView.image = [dicItem objectForKey:KEY_SELECTORITEM_IMAGE];
        
        NSString *strDetail = [dicItem objectForKey:KEY_SELECTORITEM_DETAIL];
        cell.detailTextLabel.text = strDetail;
    }
    
    // 第一个单元格不显示分割线
    UIView *vLine = [cell viewWithTag:1001];
    if (nRow == 0) {
        [vLine setHidden:YES];
    }
    else {
        [vLine setHidden:NO];
    }
    
    return cell;
}


/**
 * 处理单元格选中
 * @param   tableView               UITableView 类型，表对象
 * @param   indexPath               NSIndexPath 类型，表中选中记录的索引信息
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (m_Delegate && [m_Delegate respondsToSelector:@selector(selectItem:index:)]) {
        [m_Delegate selectItem:[m_arrItems objectAtIndex:indexPath.row]
                         index:indexPath.row];
    }
    [self close];
}


#pragma mark 生命周期
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}


- (void)dealloc {
    if (m_Delegate && [m_Delegate respondsToSelector:@selector(selectorWillDisappear:)]) {
        [m_Delegate performSelector:@selector(selectorWillDisappear:) withObject:self];
    }
}


@end
